
package Tracking;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet(name="RepeatVisitor", urlPatterns={"/RepeatVisitor"})
public class RepeatVisitor extends HttpServlet {
   

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
       boolean newbie = true;
       String strUser = "", strDate="";
       
       Cookie[] cookies = request.getCookies();     
       if(cookies != null){
           for (int i = 0; i < cookies.length; i++) {
               Cookie c = cookies[i];
               if(c.getName().equals("RepeatVisitor")){
                    strUser = c.getValue();
                    newbie =false;
               }
               
               if (c.getName().equals("AccessDate")) {
                   strDate = c.getValue();
               }
           }
       }
       
       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       String docType = "<! DOCTYPE HTML PUBLIC \"-W3C//DTD HTML 4.0" + "Transitional//EN\">\n";
       out.println(docType + "<HTML>\n" + 
               "<HEAD><TITLE>Welcome to fast run cars</TITLE></HEAD>\n" + 
               "<BODY bgcolor=\"#FDF5E6\">\n");
       
        if (newbie) {
            strUser = request.getParameter("user");
            Cookie returnVisitor = new Cookie("RepeatVisitor",strUser);
            returnVisitor.setMaxAge(60*60*24*365);
            
            response.addCookie(returnVisitor);
            out.println("<H1 ALIGN=\"CENTER\">Welcome : "+strUser+"!</H1>\n");
        }else{
            out.println("<H1 ALIGN=\"CENTER\">Welcome : "+strUser+"!</H1>\n");
            out.println("<H3 ALIGN=\"CENTER\">You visitor our site on : "+strDate+"!</H3>\n");
        }
       out.println("</BODY></HTML>");
       
       strDate = new Date().toString();
       Cookie accessDate = new Cookie("AccessDate", strDate);
       
       accessDate.setMaxAge(60*60*24*365);
       
       response.addCookie(accessDate);
    }
} 

